package io.kiki.stack.http.feign.metrics5;

import feign.Request.Options;
import io.dropwizard.metrics5.MetricRegistry;
import io.dropwizard.metrics5.Timer;

import java.io.IOException;

/**
 * Warp feign {@link Client} with metrics.
 */
public class MeteredClient extends BaseMeteredClient implements Client {

    private final Client client;

    public MeteredClient(Client client, MetricRegistry metricRegistry, MetricSuppliers metricSuppliers) {
        super(metricRegistry, new FeignMetricName(Client.class), metricSuppliers);

        this.client = client;
    }

    @Override
    public Response execute(Request request, Options options) throws IOException {
        final RequestTemplate template = request.requestTemplate();
        try (final Timer.Context timer = createTimer(template)) {
            Response response = client.execute(request, options);
            recordSuccess(template, response);
            return response;
        } catch (FeignException e) {
            recordFailure(template, e);
            throw e;
        } catch (IOException | RuntimeException e) {
            recordFailure(template, e);
            throw e;
        } catch (Exception e) {
            recordFailure(template, e);
            throw new IOException(e);
        }
    }
}
